package org.fastsyncer.sdk.client.http;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.fastsyncer.sdk.client.Connector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpConnector implements Connector {

    private static final Logger logger = LoggerFactory.getLogger(HttpConnector.class);

    private CloseableHttpClient client = HttpClients.createDefault();

    @Override
    public String send(String url, List<BasicNameValuePair> params) {
        if (logger.isDebugEnabled()) {
            logger.debug(url);
            if (null != params) {
                logger.debug(params.toString());
            }
        }
        
        String msg = null;
        CloseableHttpResponse response = null;
        try {
            // URL
            HttpPost post = new HttpPost(url);
            if (null != params) {
                post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            }
            // 发送请求
            response = client.execute(post);
            HttpEntity entity = response.getEntity();
            msg = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            logger.error(e.getLocalizedMessage());
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage());
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error(e.getLocalizedMessage());
            }
        }
        return msg;
    }

    @Override
    public void close() throws IOException {
        if (null != client) {
            client.close();
        }
    }

}
